import { Table, Popconfirm, Button } from 'antd';
import React, { useReducer, useEffect, useCallback } from 'react';
import { produce, Draft } from 'immer';
import { useApi } from 'hooklib/async';

type IProductList = { name: string }[];
type opById = (id: string) => void;

function useProductListReducer(products: IProductList) {
  const productListReducer = produce((productList: IProductList, action) => {
    switch (action.type) {
      case 'DELETE':
        const { id } = action;
        const idx = productList.findIndex(v => v.name === id);
        productList.splice(idx, 1);
    }
  });

  return useReducer(productListReducer, products);
}

const ProductList: React.FC<{
  products: IProductList;
}> = ({ products }) => {
  // const [productList, dispatch] = useReducer(productListReducer, products)
  const ts = useApi([], () => ['/dir/path']);
  console.log(ts);

  const [productList, dispatch] = useProductListReducer(products);
  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
    },
    {
      title: 'Actions',
      render: (text: any, record: any) => {
        return (
          <Popconfirm
            title="Delete?"
            onConfirm={() => dispatch({ type: 'DELETE', id: record.name })}
          >
            <Button>Delete </Button>
          </Popconfirm>
        );
      },
    },
  ];
  return (
    <div>
      <h4>{ts.o ? JSON.stringify(ts.d) : 'null'}</h4>
      <Table
        dataSource={productList as IProductList}
        columns={columns}
        rowKey="name"
      />
    </div>
  );
};

export default ProductList;
